package com.jinzhi.demo.controller;

import cn.hutool.core.date.ChineseDate;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.chinese.LunarFestival;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.poi.word.Word07Writer;
import cn.hutool.core.comparator.BaseFieldComparator;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.demo.dto.TestValidDTO;
import com.jinzhi.demo.thread.ThreadPoolTool;
import com.jinzhi.jzapi.training.pojo.CoursesListVo;
import com.jinzhi.jzsynthesize.ExcelVo.ResultEnterVo;
import com.jinzhi.jzsynthesize.ExcelVo.TikuVo;
import com.jinzhi.jzweb.dao.*;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.ExpertsService;
import com.jinzhi.jzweb.service.OrganizationNewsService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.oss.domain.FileDO;
import com.jinzhi.oss.service.OssService;
import com.jinzhi.sys.dao.UserRoleDao;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import org.apache.http.entity.ContentType;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.aspectj.weaver.patterns.TypePatternQuestions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.*;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <pre>
 * 测试专用
 * </pre>
 * 
 * <small> 2018年1月16日 | Aron</small>
 */
@RestController
@RequestMapping("/test")
//@Profile("!prod")
public class TestController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private OssService ossService;
    @Autowired
    private CertificateNewsDao certificateNewsDao;
    @Autowired
    private CertificatesDao certificatesDao;
    @Autowired
    private ConsultationsDao consultationsDao;
    @Autowired
    private CoursesDao coursesDao;
    @Autowired
    private ExpertsDao expertsDao;
    @Autowired
    private OrganizationNewsDao organizationNewsDao;
    @Autowired
    private OrganizationRolesDao organizationRolesDao;
    @Autowired
    private ExaminationResultsDao examinationResultsDao;

    @Autowired
    private  TrainingCertificatesDao trainingCertificatesDao;

    @Autowired
    private TrainingResourcesDao trainingResourcesDao;

    @Autowired
    private SysFileDao sysFileDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private TrainStudentInfoDao trainStudentInfoDao;

    @Autowired
    private ExpertsService expertsService; // 专家表服务类

    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationNewsService organizationNewsService;

    /**
     * 上传OSS接口测试类
     *
     * jz_certificate_news
     *
     * @return
     */
    @RequestMapping("/uploads1")
    public Object testOss()throws Exception{
        List<CertificateNewsDO> list= certificateNewsDao.certificateNewListX();
        for(CertificateNewsDO li:list){
            if(StringUtil.notEmpty(li.getCertificateImg())){
                String url[]=li.getCertificateImg().split("upload");
                File file1 =new File("D:/upload"+url[1]);
                System.out.println("url[0]="+url[1]);
                if(file1.exists()){
                    InputStream inputStream = new FileInputStream(file1);
                    MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                    String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                     int i=certificateNewsDao.updateCertificateX(urls,li.getId().toString());
                    System.out.println("urls="+urls);
                }
            }

        }
        return "执行完成";
    }



    @Test
    public  void  sss(){
        //
        //获取当前日期（年月日）
        LocalDate now = LocalDate.now();

        System.out.println(now);
        //根据年月日构建日期
        LocalDate of = LocalDate.of(2018, 12, 26);
        System.out.println(of);
        System.out.println(of);
        //字符串转化日期，默认按照yyyy-MM-dd格式
        LocalDate parse = LocalDate.parse("2018-12-26");
        System.out.println(parse);
        //计算两个日期时间的天数
        //获取本月的最后一天
        LocalDate lastDayOfMonth = now.with(TemporalAdjusters.lastDayOfMonth());
        long days = now.until(lastDayOfMonth, ChronoUnit.DAYS);
        System.out.println(days);
        List<Map> list=new ArrayList<>();
       Map map= new HashMap();
        map.put("name","张三");
        list.add(map);
        Map map2= new HashMap();
        map2.put("name","李四");
        list.add(map2);
        Map map3= new HashMap();
        map3.put("name","张三");
        list.add(map3);
        Map map4= new HashMap();
        map4.put("name","张三");
        list.add(map4);

       // System.out.println( list.stream().count());



        Stream<String> stream= list.stream().map(e -> e.get("name").toString()).distinct();
        stream.forEach(x-> System.out.println(x));
        List<Integer> list1=new ArrayList();
        list1.add(10);
        list1.add(20);
        list1.add(200);

        List<Integer> collect = list1.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println("list<Integer>元素倒序：" + collect );

           // List<String> s= stream.collect(Collectors.toList());

            // s.stream().distinct().forEach(System.out::println);
          //  s.stream().distinct().forEach(x ->{
          //  System.out.println(x);
         //   });


    }
//    /**
//     * 加密
//     *
//     * jz_certificates
//     *
//     * @return
//     */
//    @RequestMapping("/jiamiMobile")
//    public Object jiamiMobile()throws Exception{
//        Wrapper<UserDO> Wrapper = new EntityWrapper<UserDO>();
//        List<UserDO>  userDOS = userService.selectList(Wrapper);
//
//        int i =0;
//        for(UserDO li:userDOS) {
//            //    if(li.getId()>1397085666721157121l){
//            if(li.getId()>1327202081533353985L)
//            {
//                break;
//            }
//            if (!li.getId().toString().equals("1343490975421714434")&&!li.getId().toString().equals("1343491184738455553")&&!li.getId().toString().equals("1299165680866988034")) {
//
//            if (StringUtil.notEmpty(li.getMobile())) {
//                String jiami = MD5Utils.convertMD5(li.getMobile());
//                System.out.println("加密==" + jiami);
//                li.setMobile(jiami);
//            }
//                if (StringUtil.notEmpty(li.getNation())) {
//                    String jiami = MD5Utils.convertMD5(li.getNation());
//                    li.setNation(jiami);
//                }
//                if (StringUtil.notEmpty(li.getEducation())) {
//                    String jiami = MD5Utils.convertMD5(li.getEducation());
//                    li.setEducation(jiami);
//                }
//
//                if (StringUtil.notEmpty(li.getMajor())) {
//                    String jiami = MD5Utils.convertMD5(li.getMajor());
//                    li.setMajor(jiami);
//                }
//
//                if (StringUtil.notEmpty(li.getPoliticalAffiliation())) {
//                    String jiami = MD5Utils.convertMD5(li.getPoliticalAffiliation());
//                    li.setPoliticalAffiliation(jiami);
//                }
//            //   }
////            if (li.getId() > 1397085666721157121l) {
////                break;
////            }
//            if (StringUtil.notEmpty(li.getName())) {
//                String jiami = MD5Utils.convertMD5(li.getName());
//
//                System.out.println("加密==" + jiami);
//                String jiemi = MD5Utils.convertMD5(jiami);
//                System.out.println("jie密==" + jiemi);
//                li.setName(jiami);
//            }
//
//            if (StringUtil.notEmpty(li.getIdNumber())) {
//                String jiami = MD5Utils.convertMD5(li.getIdNumber());
//
//                li.setIdNumber(jiami);
//            }
//            if (StringUtil.notEmpty(li.getEmail())) {
//                String jiami = MD5Utils.convertMD5(li.getEmail());
//
//                li.setEmail(jiami);
//            }
//
//            if (StringUtil.notEmpty(li.getUsername())) {
//                String jiami = MD5Utils.convertMD5(li.getUsername());
//
//                li.setUsername(jiami);
//            }
//
//            if (StringUtil.notEmpty(li.getLiveAddress())) {
//                String jiami = MD5Utils.convertMD5(li.getLiveAddress());
//
//                li.setLiveAddress(jiami);
//            }
//            if (StringUtil.notEmpty(li.getOrgName())) {
//                String jiami = MD5Utils.convertMD5(li.getOrgName());
//
//                li.setOrgName(jiami);
//            }
//            if (StringUtil.notEmpty(li.getQQ())) {
//                String jiami = MD5Utils.convertMD5(li.getQQ());
//
//                li.setQQ(jiami);
//            }
//            if (StringUtil.notEmpty(li.getExperience())) {
//                String jiami = MD5Utils.convertMD5(li.getExperience());
//
//                li.setExperience(jiami);
//            }
//            if (StringUtil.notEmpty(li.getOfficialCapacity())) {
//                String jiami = MD5Utils.convertMD5(li.getOfficialCapacity());
//
//                li.setOfficialCapacity(jiami);
//            }
//
//            if (StringUtil.notEmpty(li.getProvince())) {
//                String jiami = MD5Utils.convertMD5(li.getProvince());
//
//                li.setProvince(jiami);
//            }
//
//            if (StringUtil.notEmpty(li.getCity())) {
//                String jiami = MD5Utils.convertMD5(li.getCity());
//
//                li.setCity(jiami);
//            }
//            if (StringUtil.notEmpty(li.getDistrict())) {
//                String jiami = MD5Utils.convertMD5(li.getDistrict());
//
//                li.setDistrict(jiami);
//            }
//        }
//            boolean is= userService.updateById(li);
//            if(is){
//                i++;
//            }
//        }
//        return "加密执行完成"+i+"总数居="+userDOS.size();
//    }



    /**
     * 解密
     *
     * jz_certificates
     *
     * @return
     */
    @RequestMapping("/jiemiMobile")
    public Object jiemiMobile()throws Exception{


        return "解密执行完成";
    }

    /**
     * 上传OSS接口测试类
     *
     * jz_consultations
     *
     * @return
     */
    @RequestMapping("/uploads3")
    public Object testOss3()throws Exception{
        List<ConsultationsDO> list= consultationsDao.consultaionsListX();
        for(ConsultationsDO li:list){

            String urls1=null;
            String urls=null;
            if(StringUtil.notEmpty(li.getThumbnail())){
                String url1[]=li.getThumbnail().split("upload");
                if(url1.length>1){
                    File file2 =new File("D:/upload"+url1[1]);
                    if(file2.exists()){
                        InputStream inputStream = new FileInputStream(file2);
                        MultipartFile multipartFile = new MockMultipartFile(file2.getName(), inputStream);
                        urls1= ossService.uploadUrlFileOss(multipartFile,"upload"+url1[1]);
                        System.out.println("urls1="+urls1);
                    }
                }

            }

            if(StringUtil.notEmpty(li.getFiles())){
                String url[]=li.getFiles().split("upload");
                if(url.length>1){
                    File file1 =new File("D:/upload"+url[1]);
                    System.out.println("url[0]="+url[1]);

                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                        urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);

                        System.out.println("urls="+urls);
                    }
                }


            }
            int i= consultationsDao.updateCertificateX(urls,li.getId().toString(),urls1);
        }

        return "执行完成";
    }
    /**
     * 上传OSS接口测试类
     * jz_courses
     * @return
     */
    @RequestMapping("/uploads4")
    public Object testOss4()throws Exception{
        List<CoursesListVo> list= coursesDao.couresListX();
        for(CoursesListVo li:list){
            if(StringUtil.notEmpty(li.getThumbnail())){
                String url[]=li.getThumbnail().split("upload");
                File file1 =new File("D:/upload"+url[1]);
                System.out.println("url[0]="+url[1]);
                if(file1.exists()){
                    InputStream inputStream = new FileInputStream(file1);
                    MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                    String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                    int i= coursesDao.updatecouresX(urls,li.getId().toString());
                    System.out.println("urls="+urls);
                }
            }
        }
        System.out.println("执行完成4444444444=");
        return "执行完成";
    }

    /**
     * 上传OSS接口测试类
     * jz_experts
     * @return
     */
    @RequestMapping("/uploads5")
    public Object testOss5()throws Exception{
        List<Map> list= expertsDao.ExpListX();
        for(Map li:list){
            if(StringUtil.notEmpty(li.get("enclosure").toString())){
                String url[]=li.get("enclosure").toString().split("upload");
                if(url.length>1){
                    File file1 =new File("D:/upload"+url[1]);

                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                        String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                        int i= expertsDao.updateExpX(urls,li.get("id").toString());
                        System.out.println("urls="+urls);
                    }else {
                        System.out.println("url[0]="+url[1]+"id="+li.get("id"));
                        System.out.println("未找到文件");
                    }
                }

            }
        }
        System.out.println("执行完成=------------5555555");
        return "执行完成";
    }


    /**
     * 上传OSS接口测试类
     * jz_organization_news
     * @return
     */
    @RequestMapping("/uploads6")
    public Object testOss6()throws Exception{
        List<OrganizationNewsDO> list= organizationNewsDao.organizationsListX();
        for(OrganizationNewsDO li:list){
            if(StringUtil.notEmpty(li.getCachet())){
                String url[]=li.getCachet().split("upload");
                File file1 =new File("D:/upload"+url[1]);
                System.out.println("url[0]="+url[1]);
                if(file1.exists()){
                    InputStream inputStream = new FileInputStream(file1);
                    MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                    String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                    int i= organizationNewsDao.updateorganizationsX(urls,li.getId().toString());
                    System.out.println("urls="+urls);
                }
            }
        }
        System.out.println("=执行完毕==============66666666");
        return "执行完成";
    }

    /**
     * 上传OSS接口测试类
     * jz_organization_roles
     * @return
     */
    @RequestMapping("/uploads7")
    public Object testOss7()throws Exception{
        List<Map> list= organizationRolesDao.orgRolesListX();
        for(Map li:list){
            if(li.get("enclosure")!=null){

            if(StringUtil.notEmpty(li.get("enclosure").toString())){
                String url[]=li.get("enclosure").toString().split("upload");
                File file1 =new File("D:/upload"+url[1]);
                System.out.println("url[0]="+url[1]);
                if(file1.exists()){
                    InputStream inputStream = new FileInputStream(file1);
                    MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                    String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                    int i= organizationRolesDao.updateorgRolesX(urls,li.get("id").toString());
                    System.out.println("urls="+urls);
                }
            }
            }
        }
        System.out.println("=执行完毕==============77777777777");
        return "执行完成";
    }

    /**
     * 上传OSS接口测试类
     * jz_stu_sign_up
     * @return
     */
    @RequestMapping("/uploads8")
    public Object testOss8()throws Exception{
        List<Map> list= examinationResultsDao.stusinUpListX();
        for(Map li:list){
            if(li.get("photo")!=null){

                if(StringUtil.notEmpty(li.get("photo").toString())){
                    String url[]=li.get("photo").toString().split("upload");
                    if(url.length>1){
                        File file1 =new File("D:/upload"+url[1]);
                        System.out.println("url[0]="+url[1]);
                        if(file1.exists()){
                            InputStream inputStream = new FileInputStream(file1);
                            MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                            String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                            int i= examinationResultsDao.updatestusinUpX(urls,li.get("id").toString());
                            System.out.println("urls="+urls);
                        }
                    }

                }
            }
        }
        System.out.println("=执行完毕==============88888888");
        return "执行完成";
    }

    /**
     * 上传OSS接口测试类
     * jz_training_certificates
     * @return
     */
    @RequestMapping("/uploads9")
    public Object testOss9()throws Exception{

        List<Map> list= trainingCertificatesDao.rainingListX();

        for(Map li:list){
            String urls1=null;
            String urls=null;
            if(li.get("img_url")!=null){
                if(StringUtil.notEmpty(li.get("img_url").toString())){
                    String url[]=li.get("img_url").toString().split("upload");
                    File file1 =new File("D:/upload"+url[1]);
                    System.out.println("url[0]="+url[1]);
                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                         urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                    }
                }
            }
            if(li.get("img_url_nosale")!=null){
                if(StringUtil.notEmpty(li.get("img_url_nosale").toString())){
                    String url[]=li.get("img_url_nosale").toString().split("upload");
                    File file1 =new File("D:/upload"+url[1]);
                    System.out.println("url[0]="+url[1]);
                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                         urls1= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                        System.out.println("urls="+urls);
                    }
                }
            }
            int i= trainingCertificatesDao.updatetrainingX(urls,li.get("id").toString(),urls1);
        }
        System.out.println("=执行完毕==============999999999");
        return "执行完成";
    }

    //多线程并行处理list数据集
    public void handleListMutiSchedule(List<Map> list, int taskCount){

        System.out.println("begin====================================");
        ScheduledExecutorService executorService= Executors.newScheduledThreadPool(taskCount);
        int start = 0;
        int listSize=list.size();
        //取余如果最后分配不均  多余的部分给最后一个任务执行
        int remainder=listSize%taskCount;
        //每个线程执行的数据条数
        int taskDataSize = listSize/taskCount;
        //平均分配task任务
        for(int i=0;i<taskCount;i++,start+=taskDataSize){
            int end = start + taskDataSize;
            //最后如果有分配不均的，多余部分交给最后一个任务处理
            //判断最后一个线程执行的业务逻辑
            if(i==taskCount-1){
                if(remainder!=0){
                    end=listSize;
                }
            }
            executorService.schedule(new Task(list,start,end),0, TimeUnit.SECONDS);
        }

    }
    /**
     * Task任务执行单元
     */
    private class Task implements Callable<List<Map>> {
        private List<Map> list;
        private int start;
        private int end;
        public Task(List<Map> list,int start,int end){
            this.list = list;
            this.start = start;
            this.end = end;
        }

        @Override
        public List<Map> call() throws Exception {
            Object obj = null;
            List<Map> retList = new ArrayList();
            for(int i=start;i<end;i++){
                obj = list.get(i);
                Thread.sleep(10);//

                String urls1=null;
                String urls=null;
                if(list.get(i).get("img_url")!=null){
                    if(StringUtil.notEmpty(list.get(i).get("img_url").toString())){
                        String url[]=list.get(i).get("img_url").toString().split("upload");
                        File file1 =new File("D:/upload"+url[1]);
                        System.out.println("url[0]="+url[1]);
                        if(file1.exists()){
                            InputStream inputStream = new FileInputStream(file1);
                            MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                            urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                        }
                    }
                }
                if(list.get(i).get("img_url_nosale")!=null){
                    if(StringUtil.notEmpty(list.get(i).get("img_url_nosale").toString())){
                        String url[]=list.get(i).get("img_url_nosale").toString().split("upload");
                        File file1 =new File("D:/upload"+url[1]);
                        System.out.println("url[0]="+url[1]);
                        if(file1.exists()){
                            InputStream inputStream = new FileInputStream(file1);
                            MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                            urls1= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                            System.out.println("urls="+urls);
                        }
                    }
                }
                int ippp= trainingCertificatesDao.updatetrainingX(urls,list.get(i).get("id").toString(),urls1);


                System.out.println(Thread.currentThread()+"当前处理："+obj);
                //    System.out.println(UfileUtil.uploadUFile(obj.toString(),new FileInputStream("E:\\test.png")));
            }
            //返回处理结果
            return retList ;
        }
    }

    /**
     * 未运行
     * 上传OSS接口测试类
     * jz_training_resources
     * @return
     */
    @RequestMapping("/uploads10")
    public Object testOss10()throws Exception{
        List<Map> list= trainingResourcesDao.resourcesListX();
        for(Map li:list){
            if(li.get("file_route")!=null){
                    }
                if(StringUtil.notEmpty(li.get("file_route").toString())){
                        String url[]=li.get("file_route").toString().split("upload");
                    File file1 =new File("D:/upload"+url[1]);
                    String url111=li.get("file_route").toString().substring(li.get("file_route").toString().length()-4);
                    System.out.println("后缀==="+url111);
//                    if(url111.equals(".zip")||url111.equals(".rar")) {
//                        System.out.println("结束当前循环");
//                        continue;
//                    }
                    System.out.println("url[0]="+url[1]);
                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                        String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                        int i= trainingResourcesDao.updateresourcesX(urls,li.get("id").toString());
                        System.out.println("urls="+urls);
                    }
                }
            }
        System.out.println("=执行完毕==============10101010");
        return "执行完成";
    }


    /**
     * 未运行
     * 上传OSS接口测试类
     * jz_training_resources
     * @return
     */
    @RequestMapping("/uploads11")
    public Object testOss11()throws Exception{
        System.out.println("=开始执行OSS导入==============");
        List<FileDO> list= sysFileDao.sysFileListX();
        for(FileDO li:list){

                if(StringUtil.notEmpty(li.getUrl().toString())){
                    String url[]=li.getUrl().split("upload");
                    File file1 =new File("D:/upload"+url[1]);
                    System.out.println("url[0]="+url[1]);
                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                        String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                        int i= sysFileDao.updatesysFilewX(urls,li.getId().toString());
                        System.out.println("urls="+urls);
                    }
                }
        }
        System.out.println("=开始第二个方法的执行==============");
        List<Map>  list1= userRoleDao.sysUserListX();
        for(Map li1:list1){
            if(li1.get("headPortrait")!=null){
                if(StringUtil.notEmpty(li1.get("headPortrait").toString())){
                    String url[]=li1.get("headPortrait").toString().split("upload");
                    if(url.length>1){
                        File file1 =new File("D:/upload"+url[1]);
                        System.out.println("url[0]="+url[1]);
                        if(file1.exists()){
                            InputStream inputStream = new FileInputStream(file1);
                            MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                            String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                            int i= userRoleDao.updatesysUserX(urls,li1.get("id").toString());
                            System.out.println("urls="+urls);
                        }
                    }

                }
            }
        }
        System.out.println("=开始第三个方法的执行==============");
        List<Map> mapList= trainStudentInfoDao.studenInfoListX();
        for(Map ls:mapList){
            if(ls.get("picAddress")!=null){
                if(StringUtil.notEmpty(ls.get("picAddress").toString())){
                    String url[]=ls.get("picAddress").toString().split("upload");
                    File file1 =new File("D:/upload"+url[1]);
                    System.out.println("url[0]="+url[1]);
                    if(file1.exists()){
                        InputStream inputStream = new FileInputStream(file1);
                        MultipartFile multipartFile = new MockMultipartFile(file1.getName(), inputStream);
                        String urls= ossService.uploadUrlFileOss(multipartFile,"upload"+url[1]);
                        int i= trainStudentInfoDao.updatestudenInfoX(urls,ls.get("id").toString());
                        System.out.println("urls="+urls);
                    }
                }
            }
        }

        System.out.println("=全部=======执行完毕==============1111111111111");
        return "执行完成";
    }

    @RequestMapping("/session")
    public void session(HttpServletRequest request) {
        System.out.println("request class : " + request.getClass());
        System.out.println("request session : " + request.getSession());

    }

    @RequestMapping("/redis")
    public void redis() {
        Set<String> keys = stringRedisTemplate.keys("*");
        System.out.println(keys);
        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
        stringStringValueOperations.set("Aron", "hello Aron.");
        String aron = stringStringValueOperations.get("Aron");
        System.out.println(aron);

        Long expire = stringRedisTemplate.getExpire("Aron");
        Long expire2 = stringRedisTemplate.getExpire("Aron", TimeUnit.MICROSECONDS);
        Long expire3 = stringRedisTemplate.getExpire("Aron", TimeUnit.SECONDS);
        System.out.println(expire);
        System.out.println(expire2);
        System.out.println(expire3);

    }

    @GetMapping("/see")
    public void see() {
        System.out.println("Hello World!");
//        Set<String> keys = stringRedisTemplate.keys("*");
//        System.out.println(keys);
//        ValueOperations<String, String> stringStringValueOperations = stringRedisTemplate.opsForValue();
//        stringStringValueOperations.set("Aron", "hello Aron.");
//        String aron = stringStringValueOperations.get("Aron");
//        System.out.println(aron);
//
//        Long expire = stringRedisTemplate.getExpire("Aron");
//        Long expire2 = stringRedisTemplate.getExpire("Aron", TimeUnit.MICROSECONDS);
//        Long expire3 = stringRedisTemplate.getExpire("Aron", TimeUnit.SECONDS);
//        System.out.println(expire);
//        System.out.println(expire2);
//        System.out.println(expire3);

    }

    @PostMapping("/valid")
    public void valid(@RequestBody TestValidDTO dto) {
        System.out.println(dto);
    }



    @PostMapping("/testThread")
    public void testThread() {
        Wrapper<ExpertsDO> Userwrapper = new EntityWrapper<ExpertsDO>().orderBy("id", false);
        List<ExpertsDO> list11=   expertsService.selectList(Userwrapper);

        ThreadPoolTool  threadPoolTool=new ThreadPoolTool(100,list11) ;
        try {
            threadPoolTool.excute();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("wanc");
    }



    /**
     * 填充专家表中没有机构信息的行数据
     */
    @PostMapping("/autoExportExpert")
    public void autoExportExpert(@RequestBody ExpertsDO expertsDO) {
        // 查询专家信息表得出 ids -》条件为没有机构信息的行记录
        List<ExpertsDO> expertsDOList =
                expertsService.selectList(new EntityWrapper<>(new ExpertsDO()).isNull("org_id"));

        for (ExpertsDO e : expertsDOList) {
            // 取出专家表中没有机构信息的用户id，并查询用户表取出机构id
            UserDO userDO = userService.getByUserId(e.getUserId());
            OrganizationNewsDO organizationNewsDO = new OrganizationNewsDO();
            // 如果没有机构-则增加一条机构信息，机构信息除了机构名称，还需要增加机构类型，机构类型统一为 事业单位/学校
            // 2020-12-14 zyf 修改逻辑，为防止用户随意填写机构信息，当发现机构表中不存在机构，则跳过该条信息的填充
            if (!ObjectUtils.isEmpty(userDO.getOrgId())) {
                // 填充到专家信息表中
                e.setOrgId(userDO.getOrgId());
                expertsService.insertOrUpdate(e);
            } else if (StringUtil.notEmpty(userDO.getOrgName())) {
                List<OrganizationNewsDO> orgDOList =
                        organizationNewsService.selectList(new EntityWrapper<>(
                                new OrganizationNewsDO()).like("name", userDO.getOrgName()));
                // 模糊查询到多个，或者查询不到，都表示机构名称不正确
                if (orgDOList.size() != 1)
                    continue;

                OrganizationNewsDO fillOrgDO = orgDOList.get(0);

                // 更新用户信息
                userDO.setOrgId(fillOrgDO.getId());
                userService.updateById(userDO);

                e.setOrgId(fillOrgDO.getId());
                expertsService.insertOrUpdate(e);
            }
        }
    }

    @Test
    public void aes() {
        String text = "HelloWorld";

        // key：AES模式下，key必须为16位
        String key = "1234567812345678";
        // iv：偏移量，ECB模式不需要，CBC模式下必须为16位
        String iv = "1234567812345678";

        // AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());

        // 加密并进行Base转码
        String encrypt = aes.encryptBase64(text);
        System.out.println(encrypt);

        // 解密为字符串
        String decrypt = aes.decryptStr(encrypt);
        System.out.println(decrypt);
    }
    /**
     * @param args
     */
    public static void main(String[] args) throws UnsupportedEncodingException {
//
//      AES ss=  SecureUtil.aes();
//        String ss1=  ss.encrypt("111").toString();
//        String ss2=  ss.decrypt("").toString();
//
//        System.out.println(ss1);
//        System.out.println(ss2);
//
//        //公钥加密
//        String encrypt = ss.encrypt("加密的内容", "sss").toString();
//        System.out.println("获取的加密串：" + encrypt);
//        //私钥解密
//        String decrypt = ss.decrypt(encrypt).toString();
//        System.out.println("解密之后的数据：" + decrypt);
//        Word07Writer writer = new Word07Writer();
//
//// 添加段落（标题）
//        writer.addText(new Font("方正小标宋简体", Font.PLAIN, 22), "我是第一部分", "我是第二部分");
//// 添加段落（正文）
//        writer.addText(new Font("宋体", Font.PLAIN, 22), "我是正文第一部分", "我是正文第二部分");
//// 写出到文件
//        writer.flush(FileUtil.file("D:/wordWrite.docx"));
//// 关闭
//        writer.close();
//        TestController rt=new TestController();
//        rt.word(1);
//
//        //通过公历构建
//        ChineseDate date = new ChineseDate(DateUtil.parseDate("2022-03-25"));
//// 一月
//        date.getChineseMonth();
//// 正月
//        date.getChineseMonthName();
//// 初一
//        date.getChineseDay();
//// 庚子
//        date.getCyclical();
//// 生肖：鼠
//        date.getChineseZodiac();
// 传统节日（部分支持，逗号分隔）：春节
//      String sss=  date.getFestivals();
//// 庚子鼠年 正月初一
//        date.toString();
//        Map<String, Object> dataMap = new HashMap<String, Object>();
//        dataMap.put("xytitle", "试卷测试");
//        int index = 1;
//        // 选择题
//        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();//题目
//        List<Map<String, Object>> list11 = new ArrayList<Map<String, Object>>();//答案
//        index = 1;
//        for (int i = 0; i < 5; i++) {
//
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("xzn", index + ".");
//            map.put("xztest",
//                    "(   )操作系统允许在一台主机上同时连接多台终端，多个用户可以通过各自的终端同时交互地使用计算机。");
//            map.put("ans1", "A" + index);
//            map.put("ans2", "B" + index);
//            map.put("ans3", "C" + index);
//            map.put("ans4", "D" + index);
//            list1.add(map);
//
//            Map<String, Object> map1 = new HashMap<String, Object>();
//            map1.put("fuck", index + ".");
//            map1.put("abc", "A" + index);
//            list11.add(map1);
//
//            index++;
//        }
//        dataMap.put("table1", list1);
//       // dataMap.put("table11", list11);
//
////        // 填空题
////        List<Map<String, Object>> list2 = new ArrayList<Map<String, Object>>();
////        List<Map<String, Object>> list12 = new ArrayList<Map<String, Object>>();
////        index = 1;
////        for (int i = 0; i < 5; i++) {
////
////            Map<String, Object> map = new HashMap<String, Object>();
////            map.put("tkn", index + ".");
////            map.put("tktest",
////                    "操作系统是计算机系统中的一个___系统软件_______，它管理和控制计算机系统中的___资源_________.");
////            list2.add(map);
////
////            Map<String, Object> map1 = new HashMap<String, Object>();
////            map1.put("fill", index + ".");
////            map1.put("def", "中级调度" + index);
////            list12.add(map1);
////
////            index++;
////        }
////        dataMap.put("table2", list2);
////        dataMap.put("table12", list12);
////
////        // 判断题
////        List<Map<String, Object>> list3 = new ArrayList<Map<String, Object>>();
////        List<Map<String, Object>> list13 = new ArrayList<Map<String, Object>>();
////        index = 1;
////        for (int i = 0; i < 5; i++) {
////
////            Map<String, Object> map = new HashMap<String, Object>();
////            map.put("pdn", index + ".");
////            map.put("pdtest",
////                    "复合型防火墙防火墙是内部网与外部网的隔离点，起着监视和隔绝应用层通信流的作用，同时也常结合过滤器的功能。");
////            list3.add(map);
////
////            Map<String, Object> map1 = new HashMap<String, Object>();
////            map1.put("judge", index + ".");
////            map1.put("hij", "对" + index);
////            list13.add(map1);
////
////            index++;
////        }
////        dataMap.put("table3", list3);
////        dataMap.put("table13", list13);
//
////        // 简答题
////        List<Map<String, Object>> list4 = new ArrayList<Map<String, Object>>();
////        List<Map<String, Object>> list14 = new ArrayList<Map<String, Object>>();
////        index = 1;
////        for (int i = 0; i < 5; i++) {
////
////            Map<String, Object> map = new HashMap<String, Object>();
////            map.put("jdn", index + ".");
////            map.put("jdtest", "说明作业调度，中级调度和进程调度的区别，并分析下述问题应由哪一级调度程序负责。");
////            list4.add(map);
////
////            Map<String, Object> map1 = new HashMap<String, Object>();
////            map1.put("answer", index + ".");
////            map1.put("xyz", "说明作业调度，中级调度和进程调度的区别，并分析下述问题应由哪一级调度程序负责。");
////            list14.add(map1);
////
////            index++;
////        }
////        dataMap.put("table4", list4);
////        dataMap.put("table14", list14);
//
//       // MDoc mdoc = new MDoc();
//        //mdoc.createDoc(dataMap, "E:/outFile.doc");
        TestController rt=new TestController();

       // rt.word(1);
        rt.word1(1);
    }
    //生成试卷
    public void word1(Integer examId) {

        MultipartFile multipartFile = null;
        try {
            File pdfFile = new File("D:\\2023\\jar\\20230404.xls");
            FileInputStream fileInputStream = new FileInputStream(pdfFile);
            multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<TikuVo> list = EasyPoiUtil.importExcel(multipartFile, 0, 1, TikuVo.class);
        System.out.println(list.size());
    }
    //生成试卷
    public void word(Integer examId) {

        MultipartFile multipartFile=null;
        try {
            File pdfFile = new File("D:\\2022\\题目\\广西.xls");
            FileInputStream fileInputStream = new FileInputStream(pdfFile);
             multipartFile = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<TikuVo> list = EasyPoiUtil.importExcel(multipartFile, 0, 1, TikuVo.class);



        Word07Writer word07Writer = new Word07Writer();
        word07Writer.addText(new Font("方正小标宋简体", Font.PLAIN, 22), "试卷名称：" + "金职考试试卷");
       int p=1;
        for(TikuVo li:list){
            word07Writer.addText(new Font("宋体", Font.PLAIN, 15),
                    "题目"+p++ + (li.getTigan()) + ". "  + "（" + (li.getNum() + "分）"));
            String sss[]=li.getNeirong().split(";;");

            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                    sss[0]);
            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                    sss[1]);
            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                    sss[2]);
            if(sss.length>3){
                word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
                        sss[3]);
            }

        }
        // 9、写出到文件（试卷名称.docx）
        word07Writer.flush(FileUtil.file("D:/" + Math.round(Math.random() * 100) + "广西国培试卷" + ".docx"));
        // 10、关闭
        word07Writer.close();

        // 1、得到当前试卷信息
        //Exam exam = this.getById(examId);
        // 1.1 保存试卷名称


        List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("xzn", 1 + ".");
            map.put("xztest",
                    "(   )操作系统允许在一台主机上同时连接多台终端，多个用户可以通过各自的终端同时交互地使用计算机。");
            map.put("ans1", "A选项" );
            map.put("ans2", "B选项" );
            map.put("ans3", "C选项" );
            map.put("ans4", "D选项" );
            list1.add(map);
        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("xzn", 1 + ".");
        map2.put("xztest",
                "(   )操作系统允许在一台主机上同时连接多台终端，多个用户可以通过各测试是大大达到奥迪奥迪安抚啊啊。");
        map2.put("ans1", "A选项" );
        map2.put("ans2", "B选项" );
        map2.put("ans3", "C选项" );
        map2.put("ans4", "D选项" );
        list1.add(map2);
        Map<String, Object> map2s = new HashMap<String, Object>();
        map2s.put("xzn", 1 + ".");
        map2s.put("xztest",
                "(   )操作系统允许在一台主机上同时连接多台终端，多个用户可以通过各测试是大大达到奥迪奥迪安抚啊啊。");
        map2s.put("ans1", "A选项" );
        map2s.put("ans2", "B选项" );
        map2s.put("ans3", "C选项" );
        map2s.put("ans4", "D选项" );
        list1.add(map2s);
        // 2、得到当前试卷的题目列表
        //List<Integer> quIds = quExamService.listByExamId(examId);
        // 题目列表用
//        int count = 1;
//        for (Map quId : list1) {
//
//            // 3、得到当前题目信息
//            //TypePatternQuestions.Question question = questionMapper.selectById(quId);
//
//            // 4、保存到文件中：题目 格式为（ 题目2. 多选题测试（20分））
//            word07Writer.addText(new Font("宋体", Font.PLAIN, 15),
//                    "题目" + (count++) + ". " + quId.get("xztest") + "（" + (1) + "分）");
//
//            // 5、得到每个题目的选项列表
//           // List<QuAnswerDTO> quAnswerDTOList = quAnswerService.listByQu(quId);
//
//            // 6、答案和解析
//            StringBuilder answers = new StringBuilder();
//            // 题目类型 1 单选题 2 多选题 3 判断题 4 简答题 5 填空题
//            //Integer quType = question.getQuType();
//            for (Map quAnswerDTO : list1) {
//                // 添加题目选项
//                word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
//                        quAnswerDTO.get("ans1") + "、" + quAnswerDTO.get("ans2")+ "、" + quAnswerDTO.get("ans4"));
//                // 得到题目选项的答案 1 正确答案，0 错误答案
//                Integer isRight = 1;
//                String dtoAbc = quAnswerDTO.get("ans3").toString();
//
//                // 得到正确答案
//                this.getAnswers(2, isRight, answers, dtoAbc);
//            }
//
//            // 7、得到答案并保存到文件中
//            word07Writer.addText(new Font("宋体", Font.PLAIN, 10), "答案：" + answers);
//            // 8、得到题目整体解析
//            String analysis = "测试解析";
//            word07Writer.addText(new Font("宋体", Font.PLAIN, 10),
//                    "解析：" + (Objects.isNull(analysis) ? "暂无解析" : analysis));
//        }
//
//        // 9、写出到文件（试卷名称.docx）
//        word07Writer.flush(FileUtil.file("D:/" + Math.round(Math.random() * 100) + "最后一次测试11" + ".docx"));
//        // 10、关闭
//        word07Writer.close();

    }


    /**
     * 得到答案
     *
     * @param quType  题目类型 1 单选题 2 多选题 3 判断题 4 简答题 5 填空题
     * @param isRight 是否为正确答案 1 正确答案，0 错误答案
     * @param answers 得到的答案
     * @param dtoAbc  选项ABC
     */
    private void getAnswers(Integer quType, Integer isRight, StringBuilder answers, String dtoAbc) {

        //if (quType == Constants.QU_TYPE_SINGLE && isRight == Constants.NUMBER_ONE) {
            answers.append(dtoAbc);
      //  }
       // if (quType == Constants.QU_TYPE_MULTI && isRight == Constants.NUMBER_ONE) {
            //answers.append(dtoAbc);
       // }
       // if (quType == Constants.QU_TYPE_JUDGE && isRight == Constants.NUMBER_ONE) {
           // answers.append(dtoAbc);
       // }
        //if (quType == Constants.QU_TYPE_SHORT && isRight == Constants.NUMBER_ONE) {
           // answers.append(dtoAbc);
       // }
       // if (quType == Constants.QU_TYPE_FILL && isRight == Constants.NUMBER_ONE) {
          //  answers.append(dtoAbc);
        //}
    }

    public void createDoc(Map<String,Object> dat0aMap,String fileName) throws UnsupportedEncodingException {
        //dataMap 要填入模本的数据文件
        //设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
        //这里我们的模板是放在template包下面
        //Configuration 用于读取ftl文件

        /**
         * 以下是两种指定ftl文件所在目录路径的方式，注意这两种方式都是
         * 指定ftl文件所在目录的路径，而不是ftl文件的路径
         */
        //指定路径的第一种方式（根据某个类的相对路径指定）
//                configuration.setClassForTemplateLoading(this.getClass(), "");

        //指定路径的第二种方式，我的路径是C：/a.ftl
        try {
//            configuration.setDirectoryForTemplateLoading(new File("D:/2022/题目"));
//
//        //输出文档路径及名称
//        File outFile = new File("D:\\2022\\题目\\题目测试1.doc");
//
//        //以utf-8的编码读取ftl文件
//        Template template = configuration.getTemplate("测试.ftl", "utf-8");
//       // configuration.setClassForTemplateLoading(this.getClass(), "D:\\2022\\题目\\timu.ftl");
//
//        //输出文档路径及名称

//           // OutputStreamWriter oWriter = new OutputStreamWriter(fos,"UTF-8");
//            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
//
//            //这个地方对流的编码不可或缺，使用main（）单独调用时，应该可以，但是如果是web请求导出时导出后word文档就会打不开，并且包XML文件错误。主要是编码格式不正确，无法解析。
//            //out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
//            //Writer   out = new BufferedWriter(oWriter);
            Map map=new HashMap();
            map.put("xytitle","测试啦");
            map.put("title","这是标题");
            map.put("ID","这是标题11");
            map.put("count","这是标222题11");
            Configuration configuration = new Configuration(new Version("2.3.27"));
            configuration.setDefaultEncoding("utf-8");

            /**
             * 以下是两种指定ftl文件所在目录路径的方式，注意这两种方式都是
             * 指定ftl文件所在目录的路径，而不是ftl文件的路径
             */
            //指定路径的第一种方式（根据某个类的相对路径指定）
//                configuration.setClassForTemplateLoading(this.getClass(), "");

            //指定路径的第二种方式，我的路径是C：/a.ftl
            configuration.setDirectoryForTemplateLoading(new File("D:\\2022\\题目"));

            //输出文档路径及名称
            File outFile = new File("D:\\2022\\题目\\题目221.doc");
            FileOutputStream   fos = new FileOutputStream(outFile);
            //以utf-8的编码读取ftl文件
            Template template = configuration.getTemplate("最后一次.ftl", "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);

        try {
            template.process(dat0aMap, out);
            out.close();
            fos.close();
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //System.out.println("---------------------------");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
